import * as constant from '../constant'
import request from "../request"



export const getArticlesByAuthor = (username, page) => {
    return async (dispatch) => {
        try {
            const result = await request.article.getAuthor(username, page)
            dispatch({ type: constant.ARTICLES_AUTHOR_RESULT, result })
        } catch (error) {//错误
            console.log(error);
            dispatch({ type: constant.ARTICLES_AUTHOR_RESULT, result: { status: 0, message: error.message, errors: error.errors } })
        }
    }
}

export const getArticlesByFavorite = (username) => {
    return async (dispatch) => {
        try {
            const result = await request.article.getFavorite(username, 1)
            // console.log( result)
            dispatch({ type: constant.ARTICLES_AUTHOR_RESULT, result })
        } catch (error) { // 错误
            // console.log( error);
            dispatch({ type: constant.ARTICLES_AUTHOR_RESULT, result: { status: 0, message: error.message, errors: error.errors } })
        }

    }
}

// 获取首页标签
export const getTags = () => {
    return async (dispatch) => {
        try {
            const result = await request.tag.getAll()
            console.log(result)
            dispatch({ type: constant.TAGS_GET_RESULT, result })
        } catch (error) { // 错误
            console.log(error);
            dispatch({ type: constant.TAGS_GET_RESULT, result: { status: 0, message: error.message, errors: error.errors } })
        }

    }
}

//同步tag
export const syncTag = (tag) => {
    return { type: constant.ARTICLES_TAG_SYNC, tag }
}
//同步tag
export const syncTab = (tab) => {
    return { type: constant.ARTICLES_TAB_SYNC, tab }
}
//同步tag syncPage
export const syncPage = (page) => {
    return { type: constant.ARTICLES_PAGE_SYNC, page }
}

//获取选项卡文章
export const getTabArticles = ()=>{
    return async (dispatch,getState)=>{
        try {
            const {tab,tag,currentPage} = getState().articles
            console.log('tab',tab)
            console.log('tag',tag)
            console.log('page',currentPage)
            let result= {}
            if(tab){
                if(tab==='follows'){ //获取关注文章
                    console.log('获取关注文章-456');
                    result =  await request.article.followArticles(currentPage)
                    console.log('获取关注文章-456',result);
                }else if(tab==='all'){ // 获取全局文章
                    console.log('获取全局关注文章-456');
                     result =  await request.article.all(currentPage)
                }
                console.log(result)
            }

            if(tag){
                //通过标签过滤文章
                result =  await request.article.byTag(tag,currentPage) 
            }
        
            dispatch({type:constant.ARTICLES_TAB_RESULT,result})
        } catch (error) {
            console.log(error); //请求具体错误
            dispatch({type:constant.ARTICLES_TAB_RESULT,result:{status:0,message:error.message,errors:error}}) 
        }
    }
}

